<template>
	<div>
		<el-row :gutter="20" type="flex"  class="operation">
			<el-col>
				<span>筛选器：</span>
				<el-select v-model="fieldName" placeholder="请选择字段名字" class="search-select-parent">
					<el-option class="select-more-option"
					v-for="item in fieldList"
					:key="item.fieldName"
					:label="item.fieldName"
					@click.native="handleSelectField(item)"
					:value="item.fieldName">
					</el-option>
				</el-select>
				<el-select v-model="condition" placeholder="请选择筛选条件" class="search-select-child">
					<el-option class="select-more-option"
					v-for="item in conditionList"
					:key="item.val"
					@click.native="handleSelectCondition(item)"
					:label="item.key"
					:value="item.val">
					</el-option>
				</el-select>
				<el-input  class="search-select-child" v-model="leftVal"  @input="watchContentHandle" placeholder="请输入[a,b]中的a" v-if="checkType != 'dateTime'"/>
				<el-input  class="search-select-child" v-model="rightVal"  oninput="value=value.replace(/^\.+|[^\d.]/g,'')" @input="watchContentHandle($event)" placeholder="请输入[a,b]中的b" v-if="isshowRight && checkType != 'dateTime'"/>
				<el-date-picker
					class="search-select-child"
					v-if="checkType == 'dateTime'"
					v-model="leftVal"
					type="datetime"
					placeholder="选择日期">
				</el-date-picker>
				<el-date-picker
					v-if="checkType == 'dateTime' && isshowRight"
					class="search-select-child"
					v-model="rightVal"
					type="datetime"
					placeholder="选择日期">
				</el-date-picker>
			<div class="search-btn">
				<el-button
					type="primary"
					plain
					icon="el-icon-search"
					size="mini"
					class="search-btn-item"
					@click="handleQuery"
				>查询</el-button>
				<el-button
					type="primary"
					plain
					icon="el-icon-download"
					size="mini"
					class="search-btn-item"
					@click="exportBtn"
					v-show="accessType == '2' || accessType == '3' || accessType == '4' ||accessType == '5'"
				>导出</el-button>
				<el-button
					type="primary"
					plain
					icon="el-icon-plus"
					size="mini"
					class="search-btn-item"
					v-show="(accessType == '3' || accessType == '4' ||accessType == '5') && accessType2!=2"
					@click="handleAddRow"
				>新增</el-button>
				</div>
			</el-col>
		</el-row>
			<div class="data-view-table">
				<el-table v-loading="loading" :data="previewList.list"
				  :max-height=mapHeight class="data-view-table"
				  @selection-change="handleSelectionChange"
				 	cell-class-name="timeStyle"
				 	@row-click="handleRowClick" border>
					<el-table-column  v-for="(item,index) in previewList.header" min-width="190" sortable :key="index" :label="item.filedAlias" :property="item.filedName">
						<el-table-column  min-width="230"  :label="item.filedName">
							<template  slot-scope="scope">
								<el-popover  trigger="hover" placement="top" v-if="(!scope.row.isEdit || item.primaryKey) && !scope.row.isAddRow" popper-class="popover-cell">
									<span v-if="(!scope.row.isEdit || item.primaryKey) && !scope.row.isAddRow">{{scope.row[item.filedName]}}</span>
									<div slot="reference" :class="'name-wrapper'+scope.row.id">{{scope.row[item.filedName]}}</div>
                     	</el-popover>
								<el-input v-model="scope.row[item.filedName]" v-if="(scope.row.isEdit && (!item.primaryKey && item.dataType!=='datetime' && item.dataType!=='date' && item.dataType!='timestamp')) || (scope.row.isAddRow && (item.dataType!='datetime' && item.dataType!='date' && item.dataType!='timestamp'))"/>
								<el-date-picker v-if="(item.dataType=='datetime' || item.dataType=='date' || item.dataType=='timestamp') && scope.row.isEdit || (item.dataType=='datetime' || item.dataType=='date' || item.dataType=='timestamp')&& scope.row.isAddRow"
									v-model="scope.row[item.filedName]"
									value-format="yyyy-MM-dd HH:mm:ss"
									type="datetime"
									placeholder="选择日期时间">
								</el-date-picker>
							</template>
						</el-table-column>
					</el-table-column>
					<el-table-column label="操作" align="center" width="160" fixed="right" v-if="(accessType == '3' || accessType == '4' || accessType == '5') && accessType2!=2">
						<template  slot-scope="scope">
							<el-button   type="primary"  size="mini" @click="handleEdit(scope.$index, scope.row)" v-if="(!scope.row.isEdit) && !scope.row.isAddRow" plain>
								编辑
							</el-button>
							<el-button  type="primary" size="mini" @click="handleSave(scope.$index, scope.row)" v-if="(scope.row.isEdit) || scope.row.isAddRow" plain>
								保存
							</el-button>
							<el-button  type="warning" size="mini" @click="handleExit(scope.$index, scope.row)" v-if="(scope.row.isEdit) || scope.row.isAddRow" plain>
								取消
							</el-button>
							<el-button  type="danger" size="mini"  @click="handleDelete(scope.$index, scope.row)" v-if="(!scope.row.isEdit) && !scope.row.isAddRow" plain>
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div class="not-accessType" v-if="previewList.list && (Number(accessType)<1)">
					更多数据请申请表单权限
				</div>
			</div>
		 <pagination
			v-show="total > 0"
			:total="total"
         small
			:page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize"
			@pagination="getDataViewList"
      />
	</div>
</template>
<script>
import {getDateViewList,addAndEditDateViewList,getFieldsList,dateViewExport} from "@/api/dataManagement/system/info";
import {deepEqual,filterParams,getHeight} from "@/utils/zkComm";
export default {
  name: "mapDetails",
  props:['accessType','accessType2'],
  data(){
      return {
			// 遮罩层
			loading: false,
			morehandleValue:'',
			previewList:[],
			isRowEdit:false,
			isAddRow:false,
			mapHeight:undefined,
			total:0,
			queryParams: {
            pageNum: 1,
            pageSize: 30,
				tableId:'',
         },
		   options: [{
				value: 'newCreate',
				label: '导出整表',
				icon:"el-icon-plus"
			},{
				value: 'copyValue',
				label: '导出筛选结果',
				icon:"el-icon-document-copy"
			}],
			fieldName:'',
			condition:'',
			leftVal:'',
			rightVal:'',
			fieldList:[],
			conditionList:[],
			isshowRight:false,
			checkType:'number',
      }
  },
  created(){
	  this.queryParams.tableId =   this.$route.params.tableId
	  this.getDataViewList()
	  this.getFieldsbasicList()
  },
  mounted(){
	//   this.mapHeight = getHeight(true)+30
	this.mapHeight = getHeight(true)+30
  },
  methods: {
	  // 获取数据方法
	   // 数据预览列表
      getDataViewList(){
         this.loading =true;
         getDateViewList(this.queryParams).then(res=>{
				if(res.code == 200){
					res.data.list.forEach(element => {
						element.isEdit =  false
					});
					this.previewList = res.data;
					this.total = res.data.total;
					this.loading = false;
				}
         })
      },
		handleSelectField(item){
			this.isshowRight= false;
			var numList= ['tinyint','smallint','int','integer','bigint','float','double','decimal'],
			dateList = ['date','datetime','timestamp'],
			strList = ['char','varchar','tinytext','tinyblob','blob','text','mediumblob','mediumtext','longblob','longtext']
			var str = [
				{key:'<',val:'lt'},{key:'=',val:'eq'},
			{key:'<=',val:'le'},{key:'>',val:'gt'},
			{key:'>=',val:'ge'},{key:'≠',val:'ne'},
			{key:'(a,b)',val:'(a,b)'},{key:'(a,b]',val:'(a,b]'},
			{key:'[a,b)',val:'[a,b)'},{key:'[a,b]',val:'[a,b]'},
			{key:'空值',val:'null'},{key:'非空',val:'notNull'},
			]
			if(numList.indexOf(item['dataType'])!=-1){
				this.conditionList =str
				this.checkType='number'
			} else  if(strList.indexOf(item['dataType'])!=-1){
				var dataText = str = [
				{key:'包含',val:'contain'},{key:'不包含',val:'notContain'},
				{key:'开头为',val:'startWith'},{key:'结尾为',val:'endWith'},
				{key:'精准匹配',val:'eq'},
				{key:'空值',val:'null'},{key:'非空',val:'notNull'},
				]
				this.conditionList = dataText
				this.checkType='string'
			} else if(dateList.indexOf(item['dataType'])!=-1){
				this.conditionList = str;
				this.checkType='dateTime'
			}
			this.condition = '';
			this.leftVal='';
			this.condition='';
			this.rightVal='';
		},
		handleSelectCondition(item){
			console.log(item)
			if(['(a,b)','[a,b)','(a,b]','[a,b]'].indexOf(item.key)>-1) {
				this.isshowRight= true;
			} else {
				this.isshowRight= false;
			}
		},
		handleQuery(){
			var that = this;
			that.queryParams.fieldName = undefined
			that.queryParams.condition = undefined
			that.queryParams.leftVal = undefined
			that.queryParams.condition=undefined
			if(that.fieldName){
				that.queryParams.fieldName = that.fieldName
			}
			if(that.condition){
				that.queryParams.condition = that.condition
			}
			console.log(this.checkType)
			if(that.leftVal && this.checkType !='dateTime'){
				that.queryParams.leftVal = that.leftVal.replace(/\s/g,"");
			}
			if(that.rightVal && this.checkType !='dateTime'){
				that.queryParams.rightVal = that.rightVal.replace(/\s/g,"");
			}
			console.log(that.fieldName,that.condition,that.leftVal)
			if(that.fieldName&&that.condition&&that.leftVal ||that.fieldName&&that.condition&&that.leftVal&&that.rightVal){
				that.queryParams.fieldName = that.fieldName
				that.queryParams.condition = that.condition
				if(this.checkType !='dateTime') {
					that.queryParams.leftVal = that.leftVal.replace(/\s/g,"");
				}
				if(that.leftVal&&this.checkType =='dateTime'){
					that.queryParams.leftVal = this.parseTime(new Date(that.leftVal),'{y}-{m}-{d} {h}:{i}:{s}')
				}
				if(that.rightVal && this.checkType !='dateTime'){
					that.queryParams.rightVal = that.rightVal.replace(/\s/g,"");
				}
				if(that.rightVal && this.checkType =='dateTime'){
					that.queryParams.rightVal = this.parseTime(new Date(that.rightVal),'{y}-{m}-{d} {h}:{i}:{s}')
				}
				// this.getFieldsbasicList()
				this.getDataViewList()
			} else {
				this.getDataViewList()
				// this.getFieldsbasicList()
			}
		},
	  	getFieldsbasicList(){
         getFieldsList({params:this.queryParams}).then(res=>{
            if(res.code == 200){
					this.fieldList = res.data
				}
         })
      },
		exportBtn(){
			var that = this;
			var {pageNum,pageSize} =that.queryParams
			var query =  {
					pageNum,
					pageSize,
				}
			dateViewExport({tableId: that.queryParams.tableId,query:that.queryParams}).then(res=>{
				this.download(res.msg);
			})
		},
		watchContentHandle(e){
			if(this.checkType == 'number') {
				this.leftVal =  this.leftVal.replace(/^\.+|[^\d.]/g,'')
				this.rightVal =  this.rightVal.replace(/^\.+|[^\d.]/g,'')
				console.log(this.leftVal)
			} else {
				this.leftVal =  this.leftVal;
				this.rightVal = this.rightVal;
			}
		},
	  handleRowClick(){
	  },
	  // 删除
	  handleDelete(index,row){
		   this.isRowEdit =  false
			this.isAddRow = false
			if(this.isRowEdit || this.isAddRow) {
				 this.$message({
					message: '请先保存或取消正在编辑的数据后再进行删除',
					type: 'warning'
            })
				return false
			}
			let paramsRow = filterParams(row,['isEdit'])
			addAndEditDateViewList({method:'delete',tableId:this.queryParams.tableId,data:paramsRow}).then(res=>{
				if(res.code == 200){
					this.$message({
							message: '删除成功',
							type: 'success'
					})
					this.getDataViewList()
				}
			}).catch(()=>{
				this.getDataViewList()
			})
	  },
	  handleAddRow(){
		  if(this.isRowEdit || this.isAddRow){
				this.$message({
						message: '先保存再进行新增数据',
						type: 'warning'
				})
				return false
		  }
		  var addRow = {}
		  for(var i=0;i<this.previewList.header.length;i++){
			  addRow[this.previewList.header[i].property] = null
		  }
		  addRow.isAddRow=true
		  this.isAddRow =true
		  this.previewList.list.push(addRow)
	  },
	  getpreviewList(index){
		   var previewList = this.previewList.list
			previewList[index].isEdit = !previewList[index].isEdit
			if(previewList[index].isAddRow) previewList[index].isAddRow =  false
	  },
		deepEqual(object1, object2) {
			const keys1 = Object.keys(object1);
			const keys2 = Object.keys(object2);
			function isObject(obj) {
				return Object.prototype.toString.call(obj) === '[object Object]'
			}
			if (keys1.length !== keys2.length) {
				return false;
			}
			for (const key of keys1) {
				const val1 = object1[key];
				const val2 = object2[key];
				const areObjects = isObject(val1) && isObject(val2);
				if (
					areObjects && !deepEqual(val1, val2) || !areObjects && val1 !== val2
				) {
					return false;
				}
			}
			return true;
		},
		// 编辑
		handleEdit(index,row){
				if(this.isRowEdit || this.isAddRow) {
					this.$message({
							message: '请先保存正在编辑的数据后再进行编辑',
							type: 'warning'
					})
					return false
				}
				this.getpreviewList(index);
				this.isRowEdit =  true
		},
		// 保存
		handleSave(index,row){
			this.getpreviewList(index);
			this.isRowEdit =  false
			this.isAddRow = false
			var params = {
               method:'put',
               text:'编辑'
            }
			// this.queryParams.tableId
			delete row.undefined;
			if(row.isAddRow == false){
				params.method  = 'post'
				params.text='新增'
				delete row.isAddRow;
			} else {
				params.method  = 'put'
				params.text='编辑'
			}
			let paramsRow = filterParams(row,['isEdit'])
			addAndEditDateViewList({tableId:this.queryParams.tableId,data:paramsRow,method:params.method}).then((res,err)=>{
				if(res.code == 200){
					this.$message({
							message: params.text+'成功',
							type: 'success'
					})
					this.getDataViewList()
				}
			}).catch(()=>{
				this.getDataViewList()
			})
			// if(row.isAddRow == false) {
			// 	delete row.isAddRow;
			// 	addAndEditDateViewList({method:'post',tableId:this.queryParams.tableId,data:row}).then(res=>{
			// 		if(res.code == 200){
			// 			this.getDataViewList()
			// 		}
			// 	})
			// } else {
			// 	addAndEditDateViewList({method:'put',tableId:this.queryParams.tableId,data:row}).then(res=>{
			// 		if(res.code == 200){
			// 			this.getDataViewList()
			// 		}
			// 	})
			// }

		},
		handleExit(index,row){
			if(row.isAddRow){
				var data = this.previewList.list
				data.splice(index,1)
				this.previewList.list = data
				this.isRowEdit =  false
				this.isAddRow =  false
			} else {
				this.getpreviewList(index);
				this.isRowEdit =  false
			}
			this.getDataViewList();
		},
		handleSelectionChange(){
		},
		filterParams(obj,arr){
			let result = {}
			for(var item in obj){
				if(arr.indexOf(item) == -1) {
					result[item]= obj[item]
				}
			}
			return result;
		},
		updataHandle(){
			this.fieldName = ''
			this.condition = ''
			this.leftVal = ''
			this.rightVal = ''
			this.queryParams.fieldName = undefined;
			this.queryParams.condition = undefined;
			this.queryParams.leftVal = undefined
			this.getDataViewList()
		},
		showPopover(scope){
			// console.log(this.$refs['showPopover'+index])
			// return {'overflow': 'hidden','text-overflow': 'ellipsis','display': '-webkit-box','-webkit-line-clamp': '2', '-webkit-box-orient': 'vertical'}
		}
  	},
}
// //鼠标划入滚动条展现，鼠标划出滚动条隐藏
// function scrollbarShowHidden(element){
//     element.addClass('scrollbarHide');
//     element.hover(function() {
//         element.addClass('scrollbarShow');
//     }, function() {
//         element.removeClass('scrollbarShow');
//     });

// }

// scrollbarShowHidden($('.el-table__body-wrapper'));
</script>
<style>
.data-view-table .el-date-editor.el-input{
	 width:159px!important;
 }
</style>
<style lang="scss" scoped>
/****
 reset element style
.

 */
 .data-view-table{
	 position: relative;
	.not-accessType{
      font-size: 16px;
		padding:20px;
      color: #606266;
		background: #ffe399;
		border:1px solid #ddd;
		position: absolute;
		top:50%;
		left:50%;
		margin-left:-109px;
		margin-top:-31px
	}
 }
 .el-col-3{
	 width:70px;
 }
 .el-col-2{
	 width:96px;
	 margin-right:10px;
 }
 /****
 reset element style
.

 */
 .operation {
	line-height: 43px;
	padding:10px 0;
	.search-select-child,.search-select-descen,.search-select-parent{
		margin-right:10px;
	}
	.search-select-parent{
		width:200px;
	}
	.search-select-child,.search-select-descen{
		width:180px;
	}
	.el-button--mini{
		margin-right:10px;
	}
 }
 .search-input-list{
	 overflow: hidden;
	 display: inline-block;
 }
 .search-btn{
	 display: inline-block;
	.search-btn-item{
		display: inline-block;
	}
}
</style>
